﻿import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {HttpClient, HttpHeaders, HttpRequest, HttpResponse} from '@angular/common/http';
import {BehaviorSubject, Observable} from 'rxjs';
import {User} from '../_models/user';
import {environment} from '../../environments/environment';
import {map} from 'rxjs/operators';

@Injectable({providedIn: 'root'})
export class AccountService {
  private userSubject: BehaviorSubject<User>;
  public user: Observable<User>;

  constructor(
    private router: Router,
    private http: HttpClient
  ) {
    this.userSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('user')));
    this.user = this.userSubject.asObservable();
  }

  public get userValue(): User {
    return this.userSubject.value;
  }

  login(username0, password0): Observable<HttpResponse<any>> {
    return this.http.post<User>(`${environment.apiUrl}/login`, null, {
      params: {
        username: username0,
        password: password0
      },
      observe: 'response',
      responseType: 'json'
      // withCredentials: true
    })
      .pipe(map(data => {
        localStorage.setItem('token', data.headers.get('authorization'));
        localStorage.setItem('user', JSON.stringify(data));
        if (data instanceof User) {
          this.userSubject.next(data);
        }
        return data;
      }));
  }

  register(user: User): any{
    return this.http.post<User>(`${environment.apiUrl}/register`, null, {
      params: {
        name: user.username,
        password: user.password,
        gender: user.gender,
        address: user.address,
        phone: user.phone,
        email: user.email
      },
      responseType: 'json'
    })
      .pipe(map(data => {
        return data;
      }));
  }

  userList(): any {
    return this.http.post(`${environment.apiUrl}/findAll`, null, {
      headers: {
        Authorization: localStorage.getItem('token')
      }
    })
      .pipe(map(data => {
        return data;
      }));
  }

  delete(id: string): any {
    return this.http.delete(`${environment.apiUrl}/delete`, {
      headers: {
        Authorization: localStorage.getItem('token')
      },
      params: {
        id
      }
    })
      .pipe(map(data => {
        return data;
      }));
  }

  edit(user: User): any {
    console.log(user);
    return this.http.post(`${environment.apiUrl}/edit`, user, {
      headers: {
        Authorization: localStorage.getItem('token')
      }
    })
      .pipe(map(data => {
        return data;
      }));
  }

  add(user: User): any {
    console.log(user);
    return this.http.post(`${environment.apiUrl}/add`, user, {
      headers: {
        Authorization: localStorage.getItem('token')
      }
    })
      .pipe(map(data => {
        return data;
      }));
  }
}
